package com.iteye.dwangel.util.spring;

import com.litt.core.util.StringUtils;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import java.util.Locale;
import java.util.Map;

/**
 * Override to process freemarker views.
 * Created by simon on 2015/1/26.
 */
public class LayoutFreemarkerViewResolver extends FreeMarkerViewResolver {

    /** Default layout page path */
    private String defaultLayout;
    private Map<String, String> layoutMapping;
    private Map<String, Object> extraPageBeans;

    @Override
    protected View loadView(String viewName, Locale locale) throws Exception {
        AbstractUrlBasedView view = buildView(viewName);
        View result = (View) getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, viewName);
        return (view.checkResource(locale) ? result : null);
    }

    @Override
    protected AbstractUrlBasedView buildView(String viewName) throws Exception {
        AbstractUrlBasedView view = super.buildView(viewName);
        String matchedLayout = defaultLayout;
        if (null != layoutMapping) {
            for (Map.Entry<String, String> entry : layoutMapping.entrySet()) {
                if (StringUtils.startsWith(viewName, entry.getKey())) {
                    if ("none".equals(entry.getValue())) {
                        return view;
                    }
                    matchedLayout = entry.getValue();
                    break;
                }
            }
        }
        if (view instanceof LayoutFreemarkerView) {
            ((LayoutFreemarkerView)view).setContentUrl(getPrefix() + viewName + getSuffix());
        }
        view.setUrl(getPrefix() + matchedLayout + getSuffix());
        view.addStaticAttribute("mainPage", getPrefix() + viewName + getSuffix());
        if (this.extraPageBeans != null) {
            for( Map.Entry<String, Object> entry : this.extraPageBeans.entrySet()) {
                view.addStaticAttribute(entry.getKey(), entry.getValue());
            }
        }
        return view;
    }

    public void setDefaultLayout(String defaultLayout) {
        this.defaultLayout = defaultLayout;
    }

    public void setLayoutMapping(Map<String, String> layoutMapping) {
        this.layoutMapping = layoutMapping;
    }

    public void setExtraPageBeans(Map<String, Object> extraPageBeans) {
        this.extraPageBeans = extraPageBeans;
    }
}
